package com.ft.adbix.utils.permission;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

public class PermissionActivity extends AppCompatActivity {

    private static final String PERMISSION = "permission";
    private static final int REQUEST_CODE = 1231;

    String[] permission;

    public static void requestPermission(Context context, String... permissions) {
        Intent starter = new Intent(context, PermissionActivity.class);
        starter.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        starter.putExtra(PERMISSION, permissions);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = new View(this);
        view.setBackgroundColor(Color.TRANSPARENT);
        permission = getIntent().getStringArrayExtra(PERMISSION);
        ActivityCompat.requestPermissions(this, permission, REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            PermissionUtils.PermissionRequestListener listener = PermissionUtils.getInstance().getListener();
            boolean allGranted = true;
            for (int grantResult : grantResults) {
                if (grantResult != 0) {
                    allGranted = false;
                    break;
                }
            }
            if (listener != null) {
                if (allGranted) {
                    listener.onGranted(permissions);
                } else {
                    listener.onDenied();
                }
            }
            finish();
        }
    }
}
